package com.menglei.dailytasks.m0715;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.menglei.dailytasks.R;

import java.util.IllegalFormatCodePointException;

public class MediaActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private static final String TAG = "MediaActivity";
    private SurfaceView mSurfaceView;
    private Button mBtnPlay;
    private MediaPlayer mediaPlayer;
    /**
     * 00:00
     */
    private TextView mTvStart;
    private SeekBar mSeekBar;
    /**
     * 13:14
     */
    private TextView mTvEnd;


    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG,msToMinuteSecond(mediaPlayer.getCurrentPosition()));
                    mSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                    mTvStart.setText(msToMinuteSecond(mediaPlayer.getCurrentPosition()));
                }
            });
            mHandler.postDelayed(runnable, 1000);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);
        initView();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mBtnPlay = (Button) findViewById(R.id.btn_play);
        mBtnPlay.setOnClickListener(this);
        mSurfaceView.setOnClickListener(this);
        mTvStart = (TextView) findViewById(R.id.tv_start);
        mSeekBar = (SeekBar) findViewById(R.id.seekBar);
        mSeekBar.setOnSeekBarChangeListener(this);
        mTvEnd = (TextView) findViewById(R.id.tv_end);
        mediaPlayer = MediaPlayer.create(this, R.raw.video);
        mSeekBar.setMax(mediaPlayer.getDuration());
        mTvEnd.setText(msToMinuteSecond(mediaPlayer.getDuration()));
        //Log.i(TAG, msToMinuteSecond(mediaPlayer.getDuration()));
        if (!hasPermission(this)) {
            //Log.d("是否有权限：", "是的");
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }


        ContentResolver resolver = getContentResolver();
        Cursor query = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
        String[] names = query.getColumnNames();
        for (String name : names) {
            Log.d(TAG, "name" + name);
        }
        if (query != null) {
            while (query.moveToNext()) {
                String string = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                Log.d(TAG, "strings" + string);

            }
        }
    }

    private boolean hasPermission(Context context) {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        return result == 0;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_play:
                runnable.run();
                SurfaceHolder holder = mSurfaceView.getHolder();
                mediaPlayer.setDisplay(holder);
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    mBtnPlay.setText("暂停");
                } else {
                    mediaPlayer.pause();
                    mBtnPlay.setText("播放");
                }
                break;
            case R.id.surfaceView:
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            mediaPlayer.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mediaPlayer.pause();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.start();
    }

    public String msToMinuteSecond(int ms) {
        int minute = ms / 60000;
        int second = (ms - minute * 60000) / 1000;
        return String.format("%02d:%02d", minute, second);
    }
}